<link rel="stylesheet" type="text/css" href="../css/alert.css">
<meta charset="UTF-8"/>
<?php
include_once("../functions/db_manipulate.php");

if (!init()) {
  redirect("?action=login");
}

$initiatorAction = \controller\ControllerUtil::getEncodedActionFromUrlWithParameters($_SERVER['HTTP_REFERER']);

if ($_POST['oldpass'] == '' or $_POST['pass1'] == '' or $_POST['pass2'] == '') {
  redirect("?action=msg&header=header.user.pass.change.fields.empty&body=body.user.pass.change.fields.empty&view=" . $initiatorAction);
} else if ($_POST['pass1'] != $_POST['pass2']) {
  redirect("?action=msg&header=header.user.pass.different&body=body.user.pass.different&view=" . $initiatorAction);
}

connectDB();

startTransaction();

$checkPassResultSet = null;
$changePassResultSet = null;

$userNickResultSet = mysql_query("SELECT nick FROM users WHERE id='" . mysql_real_escape_string($_SESSION['id']) . "'") or die(mysql_error());

if ($nick = mysql_fetch_assoc($userNickResultSet)) {
  $oldPass = encryptString($nick['nick'], trim($_POST['oldpass']));
  $checkPassResultSet = mysql_query("SELECT id FROM users WHERE password='" . mysql_real_escape_string($oldPass) . "' AND id = '" . $_SESSION['id'] . "'") or die(mysql_error());
  if ($check = mysql_fetch_assoc($checkPassResultSet)) {
    $newPass = encryptString($nick['nick'], trim($_POST['pass1']));
    $changePassResultSet = mysql_query("UPDATE users SET password = '" . mysql_real_escape_string($newPass) . "' WHERE id = '" . $_SESSION['id'] . "'") or die(mysql_error());
  } else {
    redirect("?action=msg&header=header.user.pass.old.incorrect&body=body.user.pass.old.incorrect&view=" . $initiatorAction);
  }
}

if ($checkPassResultSet && $changePassResultSet && $userNickResultSet) {
  commitTransaction();
  redirect("?action=msg&header=header.user.pass.change.success&body=body.user.pass.change.success&view=" . $initiatorAction);
} else {
  rollbackTransaction();
  redirect("?action=msg&header=header.user.pass.change.failed&body=body.user.pass.change.failed&view=" . $initiatorAction);
}
?>


